package com.leyou.item.service;

import com.leyou.item.pojo.Category;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    //根据父结点id查询分类列表
    public List<Category> queryListByParent(Long pid) {
        Category category = new Category();
        category.setParentId(pid);
        List<Category> list = categoryMapper.select(category);
        return list;
    }

    //根据品牌ID来查询分类信息进行回显
    public List<Category> queryByBrand(Long bid) {
        return this.categoryMapper.queryByBrand(bid);
    }

    //根据id集合，查询数据自动封装成list集合，替代了循环迭代查询
    public List<String> queryNamesByCids(List<Long> asList) {
        List<Category> categoryList = this.categoryMapper.selectByIdList(asList);
        //查询结果集合中封装的是对象，但我们只要其中的name信息
        List<String> nameList = new ArrayList<>();
        for (Category category : categoryList) {
            nameList.add(category.getName());
        }
        return nameList;
    }


    //添加分类信息
    public void addCategory(Category category) {
        this.categoryMapper.insertSelective(category);
    }
    //添加新节点的同时，修改原节点的父结点标示为1
    public void updateOldCode(Long pid) {
        this.categoryMapper.updateOldCode(pid);
    }


    //修改分类信息
    public void editCategory(Long id, String name) {
        Category category = new Category();
        category.setId(id);
        category.setName(name);
        this.categoryMapper.updateByPrimaryKeySelective(category);
    }

    //删除分类
    public void delCategory(Long id) {
        //删除子节点的parentId是参数“id”的子节点
        try {
            this.categoryMapper.delSonCode(id);
            this.categoryMapper.deleteByPrimaryKey(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据3级分类id，查询1~3级的分类
     *
     * @param id
     * @return
     */
    public List<Category> queryAllByCid3(Long id) {
        List<Category> list = new ArrayList<>();
        Category category3 = this.categoryMapper.selectByPrimaryKey(id);
        Category category2 = this.categoryMapper.selectByPrimaryKey(category3.getParentId());
        Category category1 = this.categoryMapper.selectByPrimaryKey(category2.getParentId());
        list.add(category1);
        list.add(category2);
        list.add(category3);
        return list;
    }
}
